
import java.awt.Toolkit;
import java.io.IOException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFrame;


public class KitchenStart extends javax.swing.JFrame implements DiscoveryListener {
private LocalDevice local= null;
private DiscoveryAgent agent  =null;
protected UUID uuid = new UUID(0x1101);
private Vector devices =  new Vector(),Urlconnection = new Vector();
private StreamConnection con= null;


    public KitchenStart() {
        initComponents();
error.setVisible(false);
errormsg.setVisible(false);
cancelBtn.setVisible(false);
blueStart();
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        cancelBtn = new javax.swing.JButton();
        devicecombo = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        events = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        errormsg = new javax.swing.JLabel();
        error = new javax.swing.JLabel();
        searchBtn = new javax.swing.JButton();

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        setTitle("Kitchen App");
        setResizable(false);
        setUndecorated(true);

        jPanel1.setBackground(new java.awt.Color(0, 0, 0));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Start.png"))); // NOI18N

        jPanel3.setBackground(new java.awt.Color(255, 255, 255));

        cancelBtn.setBackground(new java.awt.Color(255, 255, 255));
        cancelBtn.setForeground(new java.awt.Color(255, 255, 255));
        cancelBtn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cancel2.png"))); // NOI18N
        cancelBtn.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        cancelBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        cancelBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelBtnActionPerformed(evt);
            }
        });

        devicecombo.setFont(new java.awt.Font("Tahoma", 0, 10));
        devicecombo.setBorder(null);
        devicecombo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                devicecomboActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Arial", 0, 10));
        jLabel3.setText("Devices Discovered");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addContainerGap())
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(devicecombo, 0, 164, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(22, 22, 22))))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cancelBtn)
                    .addComponent(devicecombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(19, 19, 19))
        );

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/login2.png"))); // NOI18N

        events.setFont(new java.awt.Font("Arial", 0, 10));
        events.setForeground(new java.awt.Color(153, 153, 153));

        jButton1.setBackground(new java.awt.Color(0, 0, 0));
        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/shutd2.png"))); // NOI18N
        jButton1.setToolTipText("Exit");
        jButton1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jButton1.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/shutd.png"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        errormsg.setFont(new java.awt.Font("Arial", 0, 11));
        errormsg.setForeground(new java.awt.Color(255, 0, 0));
        errormsg.setText("Mpiksjo");

        error.setIcon(new javax.swing.ImageIcon(getClass().getResource("/error.png"))); // NOI18N
        error.setText("jLabel14");

        searchBtn.setText("Start");
        searchBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addGap(14, 14, 14)
                                    .addComponent(events, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE)
                                    .addComponent(jButton1))
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addGap(26, 26, 26)
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 238, Short.MAX_VALUE))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)))
                            .addContainerGap())
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(error, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(errormsg, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(55, 55, 55)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(107, 107, 107)
                        .addComponent(searchBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addComponent(searchBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(30, 30, 30)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(error, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(errormsg))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(events, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addComponent(jButton1)))
            .addComponent(jLabel1)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void searchBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchBtnActionPerformed
        if(local!=null){
            try {
                events.setText("Searching for Remote Devices...." );
                devices.removeAllElements();
                Urlconnection.removeAllElements();
                devicecombo.removeAllItems();
                devicecombo.setEnabled(false);
                error.setVisible(true);
                errormsg.setVisible(true);
                searchBtn.setEnabled(false);
                error.setIcon( new javax.swing.ImageIcon(getClass().getResource("/tick.png")));
                errormsg.setText("Bluetooth Enabled" );
                agent=local.getDiscoveryAgent();
                agent.startInquiry(DiscoveryAgent.GIAC, this);
            } catch (BluetoothStateException ex) {

            }
        } else{

            blueStart();
        }
}//GEN-LAST:event_searchBtnActionPerformed

    private void devicecomboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_devicecomboActionPerformed
        if(devicecombo.getSelectedItem()!=null){
            devicecombo.setEnabled(false);
            searchBtn.setEnabled(false);
            cancelBtn.setVisible(true);

            String getremoteaddr = (String) devicecombo.getSelectedItem(), remoteadd = null;
            int t = getremoteaddr.indexOf("(", 0);
            remoteadd = getremoteaddr.substring(t + 1, getremoteaddr.length() - 1);
            startservicesearch(new RemoteDevice(remoteadd) {
            });
        }
}//GEN-LAST:event_devicecomboActionPerformed

    private void cancelBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelBtnActionPerformed
        agent.cancelServiceSearch(DiscoveryAgent.GIAC);
        devicecombo.setEnabled(true);
        searchBtn.setEnabled(true);
}//GEN-LAST:event_cancelBtnActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        events.setText("Application Shuting Down...." );

        System.exit(0);
}//GEN-LAST:event_jButton1ActionPerformed
public void blueStart(){
 try {
local = LocalDevice.getLocalDevice();
 } catch (BluetoothStateException ex) {
error.setVisible(true);
error.setIcon( new javax.swing.ImageIcon(getClass().getResource("/error.png")));
errormsg.setText("No Bluetooth Stack Found." );
errormsg.setVisible(true);

        }


}
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                
              KitchenStart s = new KitchenStart();
                s.pack();
              s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               s.setLocationRelativeTo(null);
                s.setVisible(true);

            }
        });
    }


      private void startservicesearch(RemoteDevice remoteDevice) {
     UUID uuids[] = new UUID[]{uuid};
        try {
            events.setText("Searching for device servicces...." );
            agent.searchServices(null, uuids, remoteDevice, this);
             error.setVisible(false);
               errormsg.setVisible(false);

               
        } catch (BluetoothStateException ex) {
           error.setVisible(true);
           error.setIcon( new javax.swing.ImageIcon(getClass().getResource("/info.png")));
           errormsg.setText("Service Search Failed. Try Again." );
           errormsg.setVisible(true);
        }
      }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelBtn;
    private javax.swing.JComboBox devicecombo;
    private javax.swing.JLabel error;
    private javax.swing.JLabel errormsg;
    private javax.swing.JLabel events;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JButton searchBtn;
    // End of variables declaration//GEN-END:variables

    public void deviceDiscovered(RemoteDevice remote, DeviceClass arg1) {
        try {
            events.setText("Discovering Devices...." );
            if(!devices.contains(remote)){
               String friendlyname = remote.getFriendlyName(true);
                devices.addElement(friendlyname + "(" + remote + ")");
                deviceadd(devices);
events.setText("Device Found...." );
            }
        } catch (Exception e) {
        }
    }

    public void servicesDiscovered(int arg0, ServiceRecord[] arg1) {

        for (int i = 0; i < arg1.length; i++) {
            ServiceRecord rec = arg1[i];
            String url = rec.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
            events.setText("Service Search Finished...." );
DisplayKitchen(url);
        }
    }

    public void serviceSearchCompleted(int arg0, int arg1) {
        String msg = null;
        if(arg1==SERVICE_SEARCH_COMPLETED){
         
        }else{
        switch (arg1) {
         case SERVICE_SEARCH_TERMINATED:
                msg = "the service search request was cancelled ";
                break;
            case SERVICE_SEARCH_ERROR:
                msg = "an error occurred while processing the request";
                break;
            case SERVICE_SEARCH_NO_RECORDS:
                msg = "no records were found during the service search";
                break;
            case SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
                msg = "the device could not be reached";
                break;
        }
      errormsg.setText(msg);
      errormsg.setVisible(true);
      error.setVisible(true);
      error.setIcon( new javax.swing.ImageIcon(getClass().getResource("/info.png")));
      devicecombo.setEnabled(true);

        }
    }

    public void inquiryCompleted(int arg0) {

        if (devices.size() <= 0) {
            error.setVisible(true);
           errormsg.setText("No Remote Device Found");
           events.setText("No device Found...." );
           searchBtn.setEnabled(true);
        } else {
            devicecombo.setEnabled(true);
            searchBtn.setEnabled(true);
        }
        cancelBtn.setVisible(false);

    }
private void deviceadd(Vector deviced) {

if(deviced.size()<=0){
errormsg.setText("No Remote Device Found. Try Again" );
events.setText("No Device Found...." );
searchBtn.setEnabled(true);
}else{
devicecombo.setModel(new DefaultComboBoxModel(deviced));
}
}
private void DisplayKitchen(final String url) {

       
        try {
  con = (StreamConnection) Connector.open(url);
  this.setVisible(false);
  kitchenShow l = new kitchenShow(con);
  l.pack();
  l.setLocationRelativeTo(null);
  l.setVisible(true);
        } catch (IOException ex) {
        }




}

}
